<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
<body>
<input type="text" placeholder="请输入搜索关键字" id="keyword" name="keyword" size="50"> <input id="searchbtn" type="submit" value="搜">
<a href="ToAddNewsServlet">发布</a>
<table id="tbnews" border="1">
    <tr>
        <th>编号</th>
        <th>标题</th>
        <th>所属版块</th>
        <th>发布时间</th>
        <th>操作</th>
    </tr>
</table>
<a href="javascript:void(0)" id="firstpage" class="pages">首页</a>|
<a href="javascript:void(0)" id="prevpage" class="pages">上一页</a>|
<a href="javascript:void(0)" id="nextpage" class="pages">下一页</a>|
<a href="javascript:void(0)" id="lastpage" class="pages">尾页</a>
</body>
</html>
<script>
    var pageIndex;  //当前页
    var totalPage;  //总页数

    $(function () {
        var getNewsList = function (curr) {
            $.ajax({
                type: 'POST',
                url: 'NewsJsonServlet',
                dataType: 'JSON',
                data: {
                    keyword: $("#keyword").val(),
                    pageIndex: curr || 1
                },
                success: function (data) {
                    $("#tbnews").find(".contextdata").remove();
                    $.each(data.newsList, function (index, obj) {
                        var $newsstr = "<tr class='contextdata'><td>" + obj.newsid + "</td><td>" + obj.title + "</td><td>" + obj.block.blockName + "</td><td>" + obj.writeTime + "</td><td><a href='DeleteNewsServlet?newsid=" + obj.newsid + "' onclick='javascript:return delNews()'>删除</a>|<a href='GetNewsServlet?newsid=" + obj.newsid + "'>修改</a> |<a href='ViewNewsServlet?newsid=" + obj.newsid + "'>预览</a> </td></tr>";
                        $("#tbnews").append($newsstr);

                    });

                    totalPage = data.totalPages;   //页面加载，将后台传递的值，赋给全局变量，待翻页的时候，将此变量重新赋给查询函数（getNewsList）
                    pageIndex = data.pageIndex;
                }
            });
        }

        getNewsList();

        $("#searchbtn").on("click", function () {
            getNewsList();
        });

        $(".pages").on("click", function () {
            var pageflag = $(this).attr("id");

            if (pageflag == "firstpage") {
                getNewsList(1);
            } else if (pageflag == "prevpage") {
                pageIndex--;
                getNewsList(pageIndex);
            } else if (pageflag == "nextpage") {
                pageIndex++;
                if (pageIndex > totalPage) {
                    pageIndex = totalPage;
                }
                getNewsList(pageIndex);
            } else if (pageflag == "lastpage") {
                getNewsList(totalPage);
            }


        });


    });

    function delNews() {
        var answer = confirm("确认删除吗？");

        if (answer) {
            return true;
        } else {
            return false;
        }

    }

</script>

